package com.example.service.impl;

import ch.qos.logback.classic.Logger;
import com.example.entity.MessageNotice;
import com.example.entity.authority.Party;
import com.example.entity.supervision.PlanDetail;
import com.example.ext.entity.ExtSysUser;
import com.example.mapp.MessageNoticeMapp;
import com.example.mapp.PartyMapp;
import com.example.mapp.PlanDetailMapp;
import com.example.mapp.SysUserMapp;
import com.example.service.PlanDetailService;
import com.example.util.ExcelUtil;
import com.example.util.ResultUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by simon on 2018/8/9.
 */
@Service
public class PlanDetailServiceImpl implements PlanDetailService {


    private final static Logger logger = (Logger) LoggerFactory.getLogger(PlanDetailServiceImpl.class);

    @Autowired
    PlanDetailMapp planDetailMapp;

    @Autowired
    PartyMapp partyMapp;

    @Autowired
    private MessageNoticeMapp messageNoticeMapp;

    @Autowired
    private SysUserMapp sysUserMapp;

    @Override
    public Map<String, Object> query(Map map) {
        Map<String, Object> map1 = new HashMap<>();
        try {
            if (null != (map.get("currentPage")+"") && null != (map.get("pageSize")+"")) {
//                Page<Map> page = PageHelper.startPage((Integer) map.get("currentPage"),
//                        Integer.parseInt(map.get("pageSize")+""));
                map1.put("total", planDetailMapp.queryTotal(map).get("total"));
                map.put("start",((Integer) map.get("currentPage")-1)*Integer.parseInt(map.get("pageSize")+""));
                List<Map> list = planDetailMapp.query(map);
                map1.put("list", list);
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(), null);
        }
        return ResultUtil.returnSuccess("成功", map1);
    }

    @Override
    public Map<String, Object> add(PlanDetail map) {
        try {
            int i1 = planDetailMapp.insert(map);
            if (i1 >= 0) {
                return ResultUtil.returnSuccess("新增计划成功", null);
            } else {
                return ResultUtil.returnError("新增失败", null);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("新增失败", null);
        }
    }

    @Override
    @Transactional
    public Map<String, Object> inExcel(MultipartFile file, String pdictId) {
        try {
            List<List<Object>> list = ExcelUtil.getListByExcel(file.getInputStream(), file.getOriginalFilename());
            //获取导入的文件
            if(list != null && list.size() > 0){
                if(list.get(0).size()>5
                        && !"检查计划".equals(list.get(0).get(0))
                        && !"序号".equals(list.get(1).get(0))){
                    for (int i = 0; i < list.size(); i++) {

                        List listObject = list.get(i);
                        if (listObject != null && listObject.size() > 1) {
                            PlanDetail planDetail = new PlanDetail();
                            planDetail.setBeCkedPartyId(listObject.get(1)+"");
                            planDetail.setBeCkedPartyName(listObject.get(0)+"");
                            planDetail.setBePartyType(listObject.get(2)+"");
                            planDetail.setRsponPartyId(listObject.get(4)+"");
                            planDetail.setRsponPartyName(listObject.get(3)+"");
                            planDetail.setRsponUserId(listObject.get(6)+"");
                            planDetail.setRsponUserName(listObject.get(5)+"");
                            planDetail.setPlanDictId(pdictId);
                            planDetail.setIsAdjustment("0");
                            planDetail.setCheckState("0");
                            planDetailMapp.insert(planDetail);

                            String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                            MessageNotice messageNotice = new MessageNotice();
//                            messageNotice.setElevatoriType(null);
                            String content = planDetail.getRsponUserName()+"：您好，"+planDetail.getBeCkedPartyName()+" 需要进行现场监督检查，请及时处理。";
                            messageNotice.setTitle("新监督检查任务");
                            messageNotice.setContent(content);
//                            messageNotice.setElevatoriMonId(planDetail.getId()+"");
                            messageNotice.setIsRead("0");
                            messageNotice.setNoticeTime(noticeTime);
                            messageNotice.setReceivePartyId(planDetail.getRsponPartyId());
                            messageNotice.setSendUserId(null);
                            messageNotice.setReceiveUserId(planDetail.getRsponUserId());
                            messageNoticeMapp.add(messageNotice);
                        }

                    }
                }else{
                    for (int i = 2; i < list.size(); i++) {
                        List listObject = list.get(i);
                        if (listObject != null && listObject.size() > 1) {
                            //如果有单位名称
                            if(listObject.get(1)!=null && !listObject.get(1).equals("")){
                                String name = "%"+listObject.get(1)+"%";
                                List<Party> pl = partyMapp.queryByNameLk(name);
                                //根据名字只查到一条数据
                                if(pl!=null && pl.size()==1){
                                    PlanDetail planDetail = new PlanDetail();
                                    planDetail.setBeCkedPartyId(pl.get(0).getId()+"");
                                    planDetail.setBeCkedPartyName(pl.get(0).getPartyName());
                                    planDetail.setBePartyType(listObject.get(2)+"");
                                    if(listObject.get(3)!=null && !listObject.get(3).equals("")){
                                        String name1 = "%"+listObject.get(3)+"%";
                                        List<Party> pl1 = partyMapp.queryByNameLk(name1);
                                        if(pl1!=null && pl1.size()==1) {
                                            planDetail.setRsponPartyName(pl1.get(0).getPartyName());
                                            planDetail.setRsponPartyId(pl1.get(0).getId()+"");
                                        } else {
                                            planDetail.setRsponPartyName(listObject.get(3)+"");
                                        }
                                    }
                                    planDetail.setPlanDictId(pdictId);
                                    planDetail.setIsAdjustment("0");
                                    planDetail.setCheckState("0");
                                    planDetailMapp.insert(planDetail);
                                }
                            }
                        }
                    }
                }
            }

            return ResultUtil.returnSuccess("导入成功", null);
        }catch(Exception e){
            logger.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.returnError("导入失败", null);
        }
    }

    @Override
    public Map<String, Object> delete(Map map) {
        try{
            int i4 = planDetailMapp.delete(map.get("id")+"");
            if(i4>=0){
                return ResultUtil.returnSuccess("删除计划成功", null);
            }else{
                return ResultUtil.returnError("删除计划失败", null);
            }

        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError("删除计划失败", null);
        }
    }

    @Override
    public Map<String, Object> update(Map map) {
        try{
            int i2 = planDetailMapp.update(map);
            if(i2>=0){
                return ResultUtil.returnSuccess("修改计划成功", null);
            }else{
                return ResultUtil.returnError("修改计划失败", null);
            }

        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError("修改失败", null);
        }
    }

    @Override
    @Transactional
    public Map<String, Object> publish(Map map) {
        try{
        	int i3 = planDetailMapp.update(map);

            if(i3 >= 0 && "2".equals(map.get("checkType") + "")){
                String rsponUserId = map.get("rsponUserId")+"";         //负责人id
                String rsponUserName = map.get("rsponUserName")+"";     //负责人姓名
                String beCkedPartyName = map.get("beCkedPartyName")+""; //被检查机构名称
                String rsponPartyId = map.get("rsponPartyId")+"";           //计划目录id

//                String planDetailId = map.get("id")+"";                  //计划明细id

                String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

                MessageNotice messageNotice = new MessageNotice();
//                messageNotice.setElevatoriType(null);
                String content = (rsponUserName.split(","))[0]+"：您好，"+beCkedPartyName+" 需要进行现场监督检查，请及时处理。";
                messageNotice.setTitle("新监督检查任务");
                messageNotice.setContent(content);
//                messageNotice.setElevatoriMonId(planDetailId);
                messageNotice.setIsRead("0");
                messageNotice.setNoticeTime(noticeTime);
                messageNotice.setReceivePartyId(rsponPartyId);
                messageNotice.setSendUserId(null);
                messageNotice.setReceiveUserId(rsponUserId.split(",")[0]);
                messageNoticeMapp.add(messageNotice);

                if(rsponUserName.contains(",")){
                    MessageNotice messageNotice2 = new MessageNotice();
//                    messageNotice2.setElevatoriType(null);
                    String content2 = (rsponUserName.split(","))[1]+"：您好，"+beCkedPartyName+" 需要进行现场监督检查，请及时处理。";
                    messageNotice2.setTitle("新监督检查任务");
                    messageNotice2.setContent(content2);
//                    messageNotice2.setElevatoriMonId(planDetailId);
                    messageNotice2.setIsRead("0");
                    messageNotice2.setNoticeTime(noticeTime);
                    messageNotice2.setReceivePartyId(rsponPartyId);
                    messageNotice2.setSendUserId(null);
                    messageNotice2.setReceiveUserId(rsponUserId.split(",")[1]);
                    messageNoticeMapp.add(messageNotice2);
                }

                return ResultUtil.returnSuccess("发布成功", null);
            } else if(i3 >= 0 && "1".equals(map.get("checkType") + "")){
                String beCkedPartyName = map.get("beCkedPartyName")+""; // 被检查机构名称
                String rsponPartyId = map.get("rsponPartyId")+"";           // 计划目录id

                // 查询待通知用户列表
                ExtSysUser systemUser = new ExtSysUser();
                systemUser.setPartyId(Long.valueOf(rsponPartyId));
                if("5".equals(map.get("pdType"))){//委托检测
                    systemUser.setCardType("电梯检验员证,电梯检验师证");
                }else{
                    systemUser.setCardType("监察A类,监察B类");
                }

                List<ExtSysUser> userList = sysUserMapp.findSysUserList(systemUser);
                String noticeTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                String receiveUsers = "";
                String receiveUserNames = "";
                for(int i = 0,len = userList.size(); i < len; i++){
                    ExtSysUser user = userList.get(i);
                    receiveUsers += user.getId();
                    receiveUserNames += user.getUserName();
                    if(i != len - 1){
                        receiveUsers += ",";
                        receiveUserNames += ",";
                    }
                    MessageNotice messageNotice = new MessageNotice();
                    String content = user.getUserName() + "：您好，" + beCkedPartyName + " 需要进行现场监督检查，请及时处理。";
                    messageNotice.setTitle("新监督检查任务");
                    messageNotice.setContent(content);
                    messageNotice.setIsRead("0");
                    messageNotice.setNoticeTime(noticeTime);
                    messageNotice.setReceivePartyId(rsponPartyId);
                    messageNotice.setSendUserId(null);
                    messageNotice.setReceiveUserId(user.getId().toString());
                    messageNoticeMapp.add(messageNotice);
                }
                map.put("rsponUserId",receiveUsers);
                map.put("rsponUserName",receiveUserNames);
                planDetailMapp.update(map);
                return ResultUtil.returnSuccess("发布成功", null);
            } else {
                return ResultUtil.returnError("发布失败", null);
            }

        }catch (Exception e){
            logger.error(e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.returnError("发布失败", null);
        }
    }

	@Override
	public Map<String, Object> queryProgramList(Map map) {
        Map<String, Object> map1 = new HashMap<>();
        try {
        	String[] parogramList = planDetailMapp.queryProgramList(map);
            map1.put("list", parogramList);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(), null);
        }
        return ResultUtil.returnSuccess("成功", map1);
    }
}
